package com.example.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CustomRealm  extends AuthorizingRealm {

    Map<String,String> userMap = new HashMap<>(16);

    {
//        userMap.put("admin","123456");
        userMap.put("admin","f51703256a38e6bab3d9410a070c32ea");
        userMap.put("admin1","1234567");
        super.setName("customRealm");
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        //从数据库 获取角色
        Set<String> roles = getRolesByUserName();
        //从数据库 获取资源
        Set<String> permissions = getPermissionsByUserName();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }

    private Set<String> getRolesByUserName() {
        Set<String> set = new HashSet<>();
        set.add("user");
        return set;
    }

    private Set<String> getPermissionsByUserName() {
        Set<String> set = new HashSet<>();
        set.add("permit:delete");
        return set;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从 subject中获取用户名
        String userName = (String)authenticationToken.getPrincipal();
        //通过用户名到数据库获取凭证
        String password = getPasswordByUserName(userName);
        if(password == null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName,password,"customRealm");
        //盐也应该保存在数据库中
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("salt"));

        return authenticationInfo;
    }

    private String getPasswordByUserName(String userName) {
        return userMap.get(userName);
    }
}
